﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThridGroup.ERP.Application.WarehouseManagement;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.DTO.WarehouseManagement;
using ThridGroup.ERP.ProductionSystem;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
namespace ThridGroup.ERP.WarehouseManagement
{
    /// <summary>
    /// 销售退货服务，实现销售退货相关的业务逻辑
    /// </summary>
    public class SalesReturnsServices : ApplicationService, ISalesReturnsServices
    {
        /// <summary>
        /// 销售退货仓储
        /// </summary>
        private readonly IRepository<SalesReturnsModel, int> _salesReturnsRepository;
        /// <summary>
        /// 客户仓储
        /// </summary>
        private readonly IRepository<CustomerModel, int> _customerrepository;
        /// <summary>
        /// 仓库设置仓储
        /// </summary>
        private readonly IRepository<WarehouseSettingModel, int> _warehouseSettingrepository;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<SalesReturnsServices> _logger;

        /// <summary>
        /// 构造函数，注入所需的仓储依赖
        /// </summary>
        public SalesReturnsServices(IRepository<SalesReturnsModel,int> salesReturnsRepository,IRepository<CustomerModel,int> customerrepository , IRepository<WarehouseSettingModel, int> warehouseSettingrepository, ILogger<SalesReturnsServices> logger)
        {
            _salesReturnsRepository = salesReturnsRepository;
            _customerrepository = customerrepository;
            _warehouseSettingrepository = warehouseSettingrepository;
            _logger = logger;
        }
        /// <summary>
        /// 新增销售退货单
        /// </summary>
        public  async  Task<int> AddSalesReturns(CreSalesReturnsDto salesReturnsDTO)
        {
            var result = ObjectMapper.Map<CreSalesReturnsDto, SalesReturnsModel>(salesReturnsDTO);
            await _salesReturnsRepository.InsertAsync(result);
            return result.Id;
        }
        /// <summary>
        /// 分页查询销售退货单，支持退货单编号、销售订单编号、客户名称、仓库名称的模糊查询，以及单据状态的等值查询
        /// </summary>
        public async Task<(List<SalesReturnsListDto> data, int total)> GetSalesReturnsPaged(
            string returnNumber = null,
            string salesOrdersCode = null,
            string customeName = null,
            string returnsWarehouse = null,
            int? documentStatus = null,
            int pageIndex = 1,
            int pageSize = 10)
        {
            var query = await _salesReturnsRepository.GetListAsync();

            // 退货单编号模糊查询
            if (!string.IsNullOrWhiteSpace(returnNumber))
            {
                query = query.Where(x => x.ReturnNumber != null && x.ReturnNumber.Contains(returnNumber, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            // 销售订单编号模糊查询
            if (!string.IsNullOrWhiteSpace(salesOrdersCode))
            {
                query = query.Where(x => x.SalesOrdersCode != null && x.SalesOrdersCode.Contains(salesOrdersCode, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            // 客户名称模糊查询
            if (!string.IsNullOrWhiteSpace(customeName))
            {
                query = query.Where(x => x.CustomeName != null && x.CustomeName.Contains(customeName, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            // 仓库名称模糊查询
            if (!string.IsNullOrWhiteSpace(returnsWarehouse))
            {
                query = query.Where(x => x.ReturnsWarehouse != null && x.ReturnsWarehouse.Contains(returnsWarehouse, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            // 单据状态等值查询
            if (documentStatus.HasValue)
            {
                query = query.Where(x => x.DocumentStatus == documentStatus.Value).ToList();
            }

            var total = query.Count;
            var pagedData = query.OrderByDescending(x => x.Id)
                                 .Skip((pageIndex - 1) * pageSize)
                                 .Take(pageSize)
                                 .ToList();
            var result = ObjectMapper.Map<List<SalesReturnsModel>, List<SalesReturnsListDto>>(pagedData);
            return (result, total);
        }

        /// <summary>
        /// 获取所有仓库设置
        /// </summary>
        public async Task<List<WarehouseSettingDto>> GetWarehouseSettings()
        {
            try
            {
                _logger.LogInformation("开始获取所有仓库设置");

                // 从仓储获取所有仓库设置
                var entities = await _warehouseSettingrepository.GetListAsync();

                // 转换为DTO
                var result = entities.Select(e => new WarehouseSettingDto
                {
                    Id = e.Id,
                    DepotCode = e.DepotCode,
                    DepotName = e.DepotName,
                    Location = e.Location,
                    Area = e.Area,
                    Head = e.Head,
                    Remark = e.Remark
                }).ToList();

                _logger.LogInformation($"获取所有仓库设置完成，共 {result.Count} 条记录");

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有仓库设置失败");
                throw new Exception($"获取所有仓库设置失败: {ex.Message}", ex);
            }
        }


        /// <summary>
        /// 分页获取仓库设置列表，支持条件筛选
        /// </summary>
        public async Task<(List<WarehouseSettingDto> data, int total)> GetWarehouseSettingsPaged(
            string depotCode = null,
            string depotName = null,
            string location = null,
            int page = 1,
            int limit = 10)
        {
            try
            {
                _logger.LogInformation($"开始分页获取仓库设置列表，页码：{page}，每页数量：{limit}");

                // 获取所有数据
                var allData = await GetWarehouseSettings();

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(depotCode))
                {
                    allData = allData.Where(x => x.DepotCode.Contains(depotCode, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                if (!string.IsNullOrWhiteSpace(depotName))
                {
                    allData = allData.Where(x => x.DepotName.Contains(depotName, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                if (!string.IsNullOrWhiteSpace(location))
                {
                    allData = allData.Where(x => x.Location.Contains(location, StringComparison.OrdinalIgnoreCase)).ToList();
                }

                var total = allData.Count;

                // 分页
                var pagedData = allData
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                _logger.LogInformation($"分页获取完成，总记录数：{total}，当前页记录数：{pagedData.Count}");

                return (pagedData, total);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分页获取仓库设置列表失败");
                throw new Exception($"分页获取仓库设置列表失败：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 获取客户列表，支持按客户名称筛选
        /// </summary>
        public async Task<List<CustomerDTO>> ShowCustomer(int pageIndex = 1, int pageSize = 10, string? customerName = "")
        {
            var customerList = await _customerrepository.GetListAsync();
            customerList = customerList.WhereIf(!string.IsNullOrEmpty(customerName), m => m.CustomerName.Contains(customerName)).ToList();
            var result = ObjectMapper.Map<List<CustomerModel>, List<CustomerDTO>>(customerList);
            return result;
        }

        /// <summary>
        /// 删除单个退货单
        /// </summary>
        public async Task DeleteAsync(int id)
        {
            var entity = await _salesReturnsRepository.GetAsync(id);
            await _salesReturnsRepository.DeleteAsync(entity);
        }

        /// <summary>
        /// 批量删除退货单
        /// </summary>
        public async Task BatchDeleteAsync(List<int> ids)
        {
            var entities = await _salesReturnsRepository.GetListAsync(x => ids.Contains(x.Id));
            await _salesReturnsRepository.DeleteManyAsync(entities);
        }

        /// <summary>
        /// 根据ID获取退货单详情（用于反填）
        /// </summary>
        public async Task<CreSalesReturnsDto> GetByIdAsync(int id)
        {
            var entity = await _salesReturnsRepository.GetAsync(id);
            return ObjectMapper.Map<SalesReturnsModel, CreSalesReturnsDto>(entity);
        }

        /// <summary>
        /// 修改退货单
        /// </summary>
        public async Task UpdateAsync(CreSalesReturnsDto dto)
        {
            var entity = await _salesReturnsRepository.GetAsync(dto.Id);
            ObjectMapper.Map(dto, entity);
            await _salesReturnsRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 修改退货单状态（如将草稿改为完成）
        /// </summary>
        public async Task UpdateStatusAsync(int id, int documentStatus  )
        {
            var entity = await _salesReturnsRepository.GetAsync(id);
            entity.DocumentStatus = documentStatus;
            await _salesReturnsRepository.UpdateAsync(entity);
        }
    }
}
